#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# OPENUDP.PY                   -- by Dr. ZhuoQing 2020-10-25
#
# Note:
#============================================================

from head import *

#------------------------------------------------------------
PORT_NAME = "upn"
PORT_PORT = "8328"
PORT_IP   = "127.0.0.1"

#------------------------------------------------------------
if len(sys.argv) > 1:
    PORT_NAME = sys.argv[1]

if len(sys.argv) > 2:
    PORT_PORT = sys.argv[2]

if len(sys.argv) > 3:
    PORT_IP = sys.argv[3]

#------------------------------------------------------------

tspinsii("import socket\r\n")

tspinsii("#------------------------------------------------------------")
tspinsii("UDP_HOST  = \'%s\'"%PORT_IP)
tspinsii("UDP_PORT  = %s"%PORT_PORT)
tspinsii("UDP_BUFSIZE = 0x1000\r\n")

tspinsii("%s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)"%PORT_NAME)
tspinsii("%s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, UDP_BUFSIZE)"%PORT_NAME)
tspinsii("%s.settimeout(0.2)\r\n\r\n"%PORT_NAME)
tspinsii("\r\n")

tspinsii("def %ssend(data):"%PORT_NAME)
tspinsii("    ADDR = (UDP_HOST, UDP_PORT)\r\n")
tspinsii("    if type(data) != str:")
tspinsii("        data = str(data)\r\n")
tspinsii("    data = bytes(data, 'gbk')")
tspinsii("    %s.sendto(data, ADDR)\r\n"%PORT_NAME)
tspinsii("\r\n")

tspinsii("def %srecv():"%PORT_NAME)
tspinsii("    try:")
tspinsii("        data, ADDR = %s.recvfrom(UDP_BUFSIZE)"%PORT_NAME)
tspinsii("    except socket.timeout:")
tspinsii("        printf('Meter time out.')")
tspinsii("        data = ''\r\n")
tspinsii("    if len(data) > 0:")
tspinsii("        return data.decode('utf-8')")
tspinsii("    else: return ''\r\n")
tspinsii("\r\n")

tspinsii("def %sval():"%PORT_NAME)
tspinsii("    %ssend('MEMOS')\r\n"%PORT_NAME)
tspinsii("    splitstr = %srecv().split(' ')"%PORT_NAME)
tspinsii("    data = []")
tspinsii("    for val in splitstr:")
tspinsii("        if len(val) > 1:")
tspinsii("            data.append(eval(val))\r\n")
tspinsii("    return data\r\n")




#------------------------------------------------------------
#        END OF FILE : OPENUDP.PY
#============================================================
